﻿using System;
using System.Collections.Generic;
using AmazonServices.Amazon;
using DataStore.Domain;
using Condition=AmazonServices.Amazon.Condition;

namespace AmazonServices
{
    /// <summary>
    /// Amazon book service facade
    /// </summary>
    public class Books
    {

        /// <summary>
        /// Amazon access key
        /// </summary>
        private const string AccessKeyId = Keys.AccessKeyId;
        /// <summary>
        /// Amazon secret key
        /// </summary>
        private const string secretKey = Keys.SecretKey;

        /// <summary>
        /// Search index set to books.
        /// </summary>
        const string SearchIndex = "Books";

        public AmazonCovers GetImages(string[] ASINs, ResponseGroup responseGroup)
        {
            AWSECommerceServicePortTypeClient client = AmazonService.Create();
            ItemLookupRequest request = new ItemLookupRequest()
                                            {
                                                IdType = ItemLookupRequestIdType.ASIN,
                                                Condition = Condition.All,
                                                ItemId = ASINs,
                                                ResponseGroup = new string[] { responseGroup.ToStringName() }
                                            };
            ItemLookup itemLookup = new ItemLookup()
                                        {
                                            Request = new ItemLookupRequest[] {request},
                                            AWSAccessKeyId = AccessKeyId
                                        };
            var result = client.ItemLookup(itemLookup);

            AmazonCovers covers = null;
            if (result != null && result.Items != null && result.Items[0].Item != null && result.Items[0].Item[0].ImageSets != null && result.Items[0].Item[0].ImageSets[0].ImageSet != null)
            {
                var item = result.Items[0].Item[0].ImageSets[0].ImageSet[0];
                covers = new AmazonCovers()
                                          {
                                              Small = new Uri(item.SmallImage.URL),
                                              Medium = new Uri(item.MediumImage.URL),
                                              Large = new Uri(item.LargeImage.URL),
                                              Thumbnail = new Uri(item.ThumbnailImage.URL),
                                          };
            }

            return covers;
        }


        /// <summary>
        /// Searches for the specified book.
        /// </summary>
        /// <param name="book">The book.</param>
        /// <param name="page">The page.</param>
        /// <param name="responseGroup">The response group.</param>
        /// <returns>Item search response from Amazon service</returns>
        public ItemSearchResponse Search(Book book, int page, ResponseGroup responseGroup)
        {

            AWSECommerceServicePortTypeClient client = AmazonService.Create();

            // prepare an ItemSearch request
            ItemSearchRequest request = new ItemSearchRequest
                                            {
                                                ItemPage = page.ToString(),
                                                SearchIndex = SearchIndex,
                                                Title = book.Title,
                                                ResponseGroup = new string[] {responseGroup.ToStringName()}
                                            };

            ItemSearch itemSearch = new ItemSearch
                                        {
                                            Request = new ItemSearchRequest[] {request},
                                            AWSAccessKeyId = AccessKeyId
                                        };


            return client.ItemSearch(itemSearch);
        }

        /// <summary>
        /// Searches for the specified book.
        /// </summary>
        /// <param name="book">The book.</param>
        /// <param name="responseGroup">The response group.</param>
        /// <returns>Books found by Amazon service.</returns>
        public BookSearchResponse SearchParsed(Book book, int page, ResponseGroup responseGroup)
        {
            BookSearchResponse result = new BookSearchResponse();


            ItemSearchResponse response = Search(book, page, responseGroup);
            if(response == null || response.Items == null || response.Items.Length == 0 || response.Items[0].Item == null)
            {
                return null;
            }

            List<AmazonBook> books = new List<AmazonBook>();
            foreach (var item in response.Items[0].Item)
            {
                AmazonBook bookData = new AmazonBook
                                    {
                                        Title = item.ItemAttributes.Title,
                                        //Authors = item.ItemAttributes.Author,
                                        ISBN = item.ItemAttributes.EAN,
                                        Edition = item.ItemAttributes.Edition,
                                        ASIN = item.ASIN
                                    };
                if (!string.IsNullOrEmpty(item.ItemAttributes.NumberOfPages))
                {
                    int numOfPages;
                    if(Int32.TryParse(item.ItemAttributes.NumberOfPages, out numOfPages))
                    {
                        bookData.NumberOfPages = numOfPages;
                    }
                }
                if (!string.IsNullOrEmpty(item.ItemAttributes.PublicationDate))
                {
                    DateTime pubdate;
                    if(DateTime.TryParse(item.ItemAttributes.PublicationDate, out pubdate))
                    {
                        bookData.DatePublished = pubdate;
                    }
                }
                if (item.ItemAttributes.Author != null)
                {
                    List<Author> authors = new List<Author>();
                    foreach (var authorWS in item.ItemAttributes.Author)
                    {
                        string[] nameParts = authorWS.Split(' ');
                        Author author = new Author();
                        if (nameParts.Length > 0) author.FirstName = nameParts[0];
                        if (nameParts.Length > 1) author.LastName = nameParts[1];
                        authors.Add(author);
                    }
                    if(authors.Count > 0)
                    {
                        bookData.Authors = authors;
                    }
                }
                bookData.Publisher = new Company()
                                         {
                                             Name = item.ItemAttributes.Publisher
                                         };

                books.Add(bookData);
            }

            result.Books = books;
            result.ItemPage = page;
            result.TotalPages = int.Parse(response.Items[0].TotalPages);
            result.TotalResults = int.Parse(response.Items[0].TotalResults);
            return result;
        }

    }
}
